// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package androidx.gdata.blogger.testing;

import java.io.IOException;
import java.util.Random;

import androidx.gdata.blogger.BloggerServer;
import androidx.gdata.blogger.BlogCollection;
import androidx.gdata.blogger.Blog;
import androidx.gdata.blogger.BlogEntry;
import androidx.gdata.blogger.BlogEntryCollection;

/**
 * Implementation of BloggerServer which wraps another implementation and delegates
 * to it. Randomly throws exceptions in order to test error handling.
 *
 * @author Mike Jennings
 */
public class FlakyBloggerServer implements BloggerServer {
  private BloggerServer delegate;
  private Random random = new Random(System.currentTimeMillis());
  private int failurePercentage;
  
  public FlakyBloggerServer(BloggerServer delegate, int failurePercentage) {
    if (failurePercentage< 0 || failurePercentage>100) {
      throw new IllegalArgumentException("Bad percentage: " + failurePercentage);
    }
    this.delegate = delegate;
    this.failurePercentage = failurePercentage;
  }

  private synchronized void maybeThrow() throws IOException {
    int r = random.nextInt(100);
    if (r < failurePercentage) {
      throw new IOException("Simulated server error");
    }
  }

  public BlogCollection getBlogCollection() throws IOException {
    maybeThrow();
    return delegate.getBlogCollection();
  }

  public Blog postBlogEntry(Blog blog, BlogEntry entry) throws IOException {
    maybeThrow();
    return delegate.postBlogEntry(blog, entry);
  }

  public Blog editBlogEntry(BlogEntry entry) throws IOException {
    maybeThrow();
    return delegate.editBlogEntry(entry);
  }

  public void deleteBlogEntry(BlogEntry entry) throws IOException {
    maybeThrow();
    delegate.deleteBlogEntry(entry);
  }

  public BlogEntryCollection getBlogEntries(Blog blog) throws IOException {
    maybeThrow();
    return delegate.getBlogEntries(blog);
  }
}
